var express = require('express');
var axios = require("axios")
var router = express.Router();
var db = require("../model/db");
const crypto = require("crypto")//引用加密模块
var jtw = require("jsonwebtoken")


router.get("/token", async function (req, res) {
  const token = req.query.token;
  var decoded = jtw.verify(token, "xzx");
  const data = await db.User.findById(decoded);
  res.send({
    code: 0,
    msg: "",
    data
  });
})
router.post("/login", async function (req, res) {
  if (req.body.code) {
    const appid = "wxa0c17cc0536ceb68";
    const appsecret = "562137832e8869e4eca6d525e1c2d935";
    const resp = await axios.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appsecret}&js_code=${req.body.code}&grant_type=authorization_code`);
    const wxid = resp.data.openid;
    const data = await db.User.findOne({ wxid })
    let id = "";
    if (data) {

      id = jtw.sign(data._id.toString(), "xzx")
    } else {
      const data = await db.User.create({
        nickName: req.body.nickName,
        headUrl: req.body.headurl,
        wxid
      })

      id = jtw.sign(data._id.toString(), "xzx")
    }
    res.send({
      code: 0,
      msg: "",
      data: id
    })
  } else {
    const md5 = crypto.createHash("md5");
    const data = await db.User.findOne({ loginName: req.body.loginName, pwd: md5.update(req.body.pwd).digest("hex") });
    if (data) {
      res.cookie("userId", data._id.toString(), {
        signed: true
      });
      res.send({
        code: 0,
        msg: "",
        data
      });
    } else {
      res.send({
        code: 0,
        msg: "",
        data: false
      });
    }
  }
})
router.post("/add", async function (req, res) {
  const u = await db.User.findOne({
    loginName: req.body.loginName
  })
  if (u) {
    res.send({
      code: 0,
      msg: "",
      data: false
    });
    return;
  }
  const md5 = crypto.createHash("md5");
  req.body.pwd = md5.update(req.body.pwd).digest("hex");
  await db.User.create(req.body);
  res.send({
    code: 0,
    msg: "",
    data: true
  });
})
router.get("/whoami", async function (req, res) {
  const data = await db.User.findById(req.signedCookies.userId)
  res.send({
    code: 0,
    msg: "",
    data
  });
})
router.get("/all", async function (req, res) {
  let page = parseInt(req.query.page);
  let limit = parseInt(req.query.limit);
  if (!page) {
    page = 1;
  }
  if (!limit) {
    limit = 3
  }
  if (!req.query.field) {
    req.query.field = "_id";//默认按照_id排序
  }
  if (!req.query.sort) {
    req.query.sort = "asc";//默认按照升序排序
  }
  //拼接排序字符串
  let s = req.query.field;
  if (req.query.sort === "desc") {
    s = "-" + s;
  }
  let condition = {};
  if (req.query.key) {
    const exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询正则表达式
    condition = {
      $or: [
        { mobile: { $regex: exp } },
        { pwd: { $regex: exp } },
        { loginName: { $regex: exp } },
        { role: { $regex: exp } }
      ]
    }
  }
  const data = await db.User.find(condition).sort(s).skip((page - 1) * limit).limit(limit);
  res.send({
    code: 0,
    msg: "",
    count: await db.User.countDocuments(condition),
    data
  });
})
router.get('/:id', async function (req, res) {
  const data = await db.User.findById(req.params.id)
  res.send({
    code: 0,
    msg: "",
    data
  })
})
router.delete("/:id", async function (req, res) {
  await db.User.deleteOne({
    _id: req.params.id
  })
  res.send({
    code: 0,
    msg: "",
    data: true
  });
})
router.put("/:id", async function (req, res) {
  const md5 = crypto.createHash("md5");
  if (req.body.pwd) {
    req.body.pwd = md5.update(req.body.pwd).digest("hex");
  }
  await db.User.updateOne({
    _id: req.params.id
  }, req.body)
  res.send({
    code: 0,
    msg: "",
    data: true
  })
})

module.exports = router;
